<template>
	<div>
		<el-dialog
			:title="title"
			:visible.sync="visible"
			:close-on-click-modal="false"
			append-to-body
			width="60%"
			:before-close="dialogBeforeClose"
			@closed="handlerClosed"
		>
			<el-form
				ref="form"
				:model="formData"
				:rules="rules"
				label-width="120px"
				:inline="false"
				size="normal"
			>
				<el-row>
					<el-col :span="12">
						<el-form-item label="名称" prop="name">
							<el-input v-model="formData.name" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="banneIconClass" label="图片" prop="banneHref">
							<el-upload
								class="avatar-uploader"
								:action="uploadFileUrl"
								:show-file-list="false"
								:data="paramsData"
								:on-success="handleSuccess"
								:before-upload="beforeUploadPicture"
								:headers="headers"
							>
								<img v-if="imageUrl" :src="imageUrl" class="avatar" />
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="文章" prop="articleInformationId">
							<el-select
								v-model="formData.articleInformationId"
								placeholder="请选择"
								clearable
							>
								<el-option
									v-for="item in articleList"
									:key="item.id"
									:label="item.title"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="是否发布" prop="releaseFlag">
							<el-switch
								v-model="formData.releaseFlag"
								active-color="#13ce66"
								inactive-color="#ff4949"
								active-value="0"
								inactive-value="1"
							></el-switch>
						</el-form-item>
					</el-col>
					<el-col v-if="formData.releaseFlag == '0'" :span="12">
						<el-form-item label="发布单位" prop="releaseCompany">
							<el-input v-model="formData.releaseCompany" clearable />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row v-if="formData.releaseFlag == '0'">
					<el-col :span="24">
						<el-form-item label="有效时间" prop="startEndTimes">
							<el-date-picker
								v-model="formData.startEndTimes"
								type="datetimerange"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								:picker-options="pickerOptions"
							>
							</el-date-picker>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item>
					<el-button type="primary" size="medium" @click="onSubmit">
						确定
					</el-button>
					<el-button size="medium" @click="handlerCancel"> 取消 </el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>

<script>
import { fileURLConfig, delImageUpload } from '@/http/upLoad'
export default {
	props: {
		banneData: {
			type: Object,
			default: () => {
				return {}
			},
		},
		visible: {
			type: Boolean,
			default: false,
		},
		title: {
			type: String,
			default: '',
		},
		dialogType: {
			type: String,
			default: '',
		},
		articleList: {
			type: Array,
			default: () => {
				return []
			},
		},
	},
	data() {
		// var startEndTimesValidator = this.startEndTimesFun
		return {
			banneIcon: '',
			relativeFolderImageUrl: '',
			imageUrl: '',
			oldImageUrl: '',
			uploadFileUrl: fileURLConfig.uploadPicture,
			paramsData: {
				folderName: fileURLConfig.uploadBanneFolderName,
			},
			rules: {
				name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
				banneHref: [{ required: true, message: '请输入名称', trigger: 'blur' }],
				startEndTimes: [
					{ required: true, message: '请选择有效时间', trigger: 'blur' },
					// { validator: startEndTimesValidator, trigger: 'blur' },
				],
			},
			pickerOptions: {
				disabledDate: time => {
					return time.getTime() < Date.now() - 8.64e7
				},
			},
		}
	},
	computed: {
		formData() {
			return this.banneData
		},
		headers() {
			let token = JSON.parse(window.localStorage.getItem('userMsg')).token
			return {
				Authorization: token,
			}
		},
	},
	watch: {
		visible(isFlag) {
			if (isFlag) {
				this.imageUrl = this.formData.banneHref
				if (this.dialogType == '2') {
					this.oldImageUrl = this.formData.banneHref
				}
			}
		},
	},
	methods: {
		startEndTimesFun(rule, value, callback) {
			if (value && value.length > 0) {
				if (new Date(value[0]).getTime() >= new Date(value[1]).getTime()) {
					callback(new Error('有效期时间范围有误'))
					return
				}
				if (new Date(value[1]).getTime() <= new Date().getTime()) {
					callback(new Error('有效期时间范围有误'))
					return
				}
				callback()
			}
		},
		// 文件上传前置方法
		beforeUploadPicture(file) {
			const isImage =
				file.type === 'image/png' ||
				file.type === 'image/jpg' ||
				file.type === 'image/jpeg'
			const isLt2M = file.size < 1024 * 1024 * 2
			if (!isImage) {
				this.$message.error('上传只能是png,jpg格式!')
			}
			if (!isLt2M) {
				this.$message.error('上传图片大小不能超过 2MB!')
			}
			return isImage && isLt2M
		},
		handleSuccess(res, file) {
			this.imageUrl = URL.createObjectURL(file.raw)
			if (file.response.head.code == '200') {
				this.banneIcon = file.response.data[0].httpImageUrl
				this.formData.banneHref = this.banneIcon
			}
			if (this.relativeFolderImageUrl) {
				if (this.dialogType == '1') {
					delImageUpload({
						imagePath: this.relativeFolderImageUrl,
					}).then(({ data }) => {
						if (data.head.code == '200') {
							this.relativeFolderImageUrl =
								file.response.data[0].relativeFolderImageUrl
						}
					})
				} else {
					if (this.oldImageUrl != this.relativeFolderImageUrl) {
						delImageUpload({
							imagePath: this.relativeFolderImageUrl,
						}).then(({ data }) => {
							if (data.head.code == '200') {
								this.relativeFolderImageUrl =
									file.response.data[0].relativeFolderImageUrl
							}
						})
					}
				}
			} else {
				this.relativeFolderImageUrl =
					file.response.data[0].relativeFolderImageUrl
			}
		},
		dialogBeforeClose() {
			this.$emit('update:visible', false)
		},
		handlerClosed() {
			if (this.banneIcon) {
				delImageUpload({
					imagePath: this.relativeFolderImageUrl,
				}).then(({ data }) => {
					if (data.head.code == '200') {
						this.imageUrl = ''
						this.relativeFolderImageUrl = ''
					}
				})
			}
			this.banneIcon = ''
			this.imageUrl = ''
			this.$emit('update:banneData', {
				name: '',
				banneHref: '',
				articleInformationId: '',
				releaseFlag: '1',
				effectiveStartTime: null,
				effectiveEndTime: null,
				startEndTimes: [],
			})
			this.handlerResetFields()
		},
		onSubmit() {
			this.$refs.form.validate(valid => {
				if (valid) {
					// 如果是修改删除原图片
					if (this.dialogType != '1') {
						if (this.oldImageUrl) {
							let delOldImageUrl = this.oldImageUrl.split('file/')[1]
							delImageUpload({
								imagePath: delOldImageUrl,
							}).then(({ data }) => {
								if (data.head.code == '200') {
									this.imageUrl = ''
									this.relativeFolderImageUrl = ''
								}
							})
						}
					}
					if (this.banneIcon) {
						this.formData.banneHref = this.banneIcon
					}
					if (this.formData.releaseFlag == '0') {
						if (
							this.formData.startEndTimes &&
							this.formData.startEndTimes.length > 0
						) {
							this.formData.effectiveStartTime = this.formData.startEndTimes[0]
							this.formData.effectiveEndTime = this.formData.startEndTimes[1]
						}
					}
					this.$emit('submit', this.formData, this.dialogType)
					this.banneIcon = ''
					this.handlerCancel()
				} else {
					return false
				}
			})
		},
		handlerCancel() {
			this.handlerResetFields()
			this.dialogBeforeClose()
			this.handlerClosed()
		},
		handlerResetFields() {
			this.$nextTick(() => {
				this.$refs['form'].clearValidate()
			})
		},
	},
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}
.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 100px;
	height: 100px;
	line-height: 100px;
	text-align: center;
}
.avatar {
	width: 100px;
	height: 100px;
	display: block;
}
.banneIconClass {
	position: absolute;
	top: 0;
	left: 51%;
}
</style>
